import 'package:flutter/material.dart';
import 'package:juju/conf/IMConf.dart';
import 'package:juju/control/JmessageCtl.dart';
import 'package:juju/default/NaviPages.dart';
import 'package:juju/default/WelcomPage.dart';
import 'package:juju/model/UserInfoModel.dart';
import 'package:juju/sub-pages/AddFriendPage.dart';
import 'package:juju/sub-pages/ChatPage.dart';
import 'package:juju/sub-pages/NewFriendsPage.dart';
import 'package:juju/sub-pages/SettingPage.dart';

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppstate();
}

class _MyAppstate extends State<MyApp> {
  ThemeData appTheme = ThemeData(
    primaryColor: Colors.grey[300],
  );

  bool _login = UserInfoModel.getInstance().login;

  Map<String, Widget Function(BuildContext)> routes = {
    "Welcome": (context) => const WelcomePage(),
    "NaviPages": (context) => const NaviPages(),
    "ChatPage": (context) => const ChatPage(),
    "AddFriend": (context) => const AddFriend(),
    "NewFriends": (context) => const NewFriendsPage(),
    "SettingPage": (context) => const SettingPage(),
  };

  @override
  void initState() {
    super.initState();

    ///===================================
    /// 初始化IM组件
    ///===================================
    IMConf.getInstance().initJmessage();

    ///====================================
    /// 获取当前用户信息，判断是否登陆
    ///====================================
    _checkLogin();
    // getCurrentUserInfoCtrl(IMConf.getInstance().getJmessage());

    ///===================================
    /// 添加好友事件监听
    ///===================================
    addContactNotifyListenerCtl();
  }

  @override
  Widget build(BuildContext context) {
    print("==================== 构建UI ======================\n");
    // bool a = UserInfoModel.getInstance().login;
    return MaterialApp(
      title: "聚聚",
      theme: appTheme,
      routes: routes,
      home: _login ? const NaviPages() : const WelcomePage(),
    );
  }

  void _checkLogin() async {
    await getCurrentUserInfoCtl(IMConf.getInstance().getJmessage());
    print("更新视图");
    setState(() {
      _login = UserInfoModel.getInstance().login;
    });
  }
}
